package com.dronff.parser;

import com.dronff.protocol.TangProtocol;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.buffer.ByteBuf;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class TangProtocolParser extends AbstractProtocolParser<TangProtocol>{
    static ObjectMapper objectMapper = new ObjectMapper();
    static final Logger logger = Logger.getLogger(TangProtocolParser.class);
    @Override
    public TangProtocol parseBytes(ByteBuf byteBuf) throws IOException {
        if (byteBuf.readableBytes() < (4 + 1)) {
            logger.debug("包长度不足4字节");
        }
        byteBuf.readChar();
        int packetSize = byteBuf.readInt();
        byte[] entity = new byte[packetSize];
        byteBuf.readBytes(entity);
        return objectMapper.readValue(entity,TangProtocol.class);
    }

    private String readClazzName(ByteBuf buf){
        assert buf.readableBytes() > 4;
        int clazzNameLength = buf.readInt();
        assert buf.readableBytes() > clazzNameLength;
        byte[] clazzName = new byte[clazzNameLength];
        buf.readBytes(clazzName);
        String clazzNameSeri = new String(clazzName,0,clazzNameLength, StandardCharsets.UTF_8);
        logger.debug("请求的类:" + clazzNameSeri);
        return clazzNameSeri;
    }

    /**
     * methodname格式：[method name]:[类型1全限定类名],[类型2全限定类名]:返回值类型
     * @param buf
     * @return
     */
    private String readMethodName(ByteBuf buf){
        assert buf.readableBytes() > 4;
        int methodNameLength = buf.readInt();
        assert buf.readableBytes() > methodNameLength;
        byte[] methodName = new byte[methodNameLength];
        buf.readBytes(methodName);
        String methodNameSeri = new String(methodName,0,methodNameLength, StandardCharsets.UTF_8);
        logger.debug("请求的方法:" + methodNameSeri);
        return methodNameSeri;
    }
}
